﻿using System;
using System.IO;

namespace Lucene.Net.Store.S3 {

	public class StreamInput : Stream {
		private Lucene.Net.Store.IndexInput input;

		public StreamInput(Lucene.Net.Store.IndexInput input) {
			this.input = input;
		}

		public override Boolean CanRead { get { return true; } }
		public override Boolean CanSeek { get { return true; ; } }
		public override Boolean CanWrite { get { return false; } }
		public override void Flush() { }
		public override Int64 Length { get { return this.input.Length(); } }

		public override Int64 Position {
			get { return this.input.GetFilePointer(); }
			set { this.input.Seek(value); }
		}

		public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count) {
			Int64 position = this.input.GetFilePointer();
			try {
				Int64 length = this.input.Length();
				if (count > (length - position)) {
					count = (Int32)(length - position);
				}
				this.input.ReadBytes(buffer, offset, count);
			}
			catch (Exception) { }
			return (Int32)(this.input.GetFilePointer() - position);
		}

		public override Int64 Seek(Int64 offset, SeekOrigin origin) {
			switch (origin) {
				case SeekOrigin.Begin:
					this.input.Seek(offset);
					break;
				case SeekOrigin.Current:
					this.input.Seek(this.input.GetFilePointer() + offset);
					break;
				case SeekOrigin.End:
					throw new NotImplementedException();
			}
			return this.input.GetFilePointer();
		}

		public override void SetLength(Int64 value) {
			throw new NotImplementedException();
		}

		public override void Write(Byte[] buffer, Int32 offset, Int32 count) {
			throw new NotImplementedException();
		}

		public override void Close() {
			this.input.Close();
			base.Close();
		}
	}
}